package com.yzt.zhuju.webview;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.web.WebRouterEvent;
import com.yzt.zhuju.event.web.WebViewEvent;
import com.yzt.zhuju.network.config.ApiConstant;
import com.yzt.zhuju.permission.PermissionsUtils;
import com.yzt.zhuju.utils.DeviceUtils;
import com.yzt.zhuju.utils.SDKInitManager;
import com.yzt.zhuju.utils.ViewUtils;
import com.yzt.p_base.utils.AppInfoUtils;

import org.json.JSONException;

import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * author : bob
 * date   : 2022/12/9
 * desc   :
 */
public class XysJavaScriptInterface {

    private final Context context;

    private final WebView mWebView;

    private Subscription subscription;

    public XysJavaScriptInterface(Context context, WebView webView) {

        this.context = context;
        this.mWebView = webView;

        subscription = RxBus.getDefault().observerRxBus(WebViewEvent.class, new Action1<WebViewEvent>() {
            @Override
            public void call(WebViewEvent event) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.evaluateJavascript("javascript:onResume()", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {

                            }
                        });
                    }
                });
            }
        });
    }

    public void onDerstoy() {
        if (subscription == null) {
            return;
        }
        if (subscription.isUnsubscribed()) {
            return;
        }
        subscription.unsubscribe();
        if (subscription != null) {
            if (!subscription.isUnsubscribed()) {
                subscription.unsubscribe();
            }
            subscription = null;
        }
    }

    @JavascriptInterface
    public void webGoBack(int type) {
        if (!(context instanceof Activity)) {
            return;
        }
        ((Activity) context).finish();
    }

    @JavascriptInterface
    public int webGetStatusBarHeight() {
        return ViewUtils.getStatusBarHeight(context);
    }

    @JavascriptInterface
    public String getAppConfig() {
        String token = RXingUtils.getLoginToken();
        JSONObject mJSONObject = new JSONObject();
        mJSONObject.put("apiToken", token);
        if (!SDKInitManager.isFirstInstalled()) {
            mJSONObject.put("deviceId", DeviceUtils.getDeviceUuid(AppConfig.application).replace("-", ""));
        }
        mJSONObject.put("deviceType", "2"); //1:ios 2:android
        mJSONObject.put("deviceBrand", DeviceUtils.getDeviceBrand());
        mJSONObject.put("apiVersion", ApiConstant.SERVICE_API_VERSION);
        mJSONObject.put("appOsVersion", DeviceUtils.getSysVersion());
        mJSONObject.put("appVersionCode", AppInfoUtils.getAppVersionCode(AppConfig.context) + "");
        mJSONObject.put("appVersionName", AppInfoUtils.getAppVersionName(AppConfig.context));
        mJSONObject.put("appPackage", AppInfoUtils.getAppPackageName());
        mJSONObject.put("channel", AppInfoUtils.getAppMetaData("UMENG_CHANNEL"));
        mJSONObject.put("h", ApiConstant.SERVICE_API_VERSION);
        return mJSONObject.toJSONString();
    }

    @JavascriptInterface
    public void updateWallet() {
        if (!(context instanceof Activity)) {
            return;
        }
        ((Activity) context).finish();
    }

    @JavascriptInterface
    public void sensors(String name, String json) {
        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(json);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void save2Photos(String... imageUrl) {
        if (imageUrl == null || imageUrl.length == 0) {
            return;
        }
        if (!(context instanceof Activity)) {
            return;
        }
        AndroidSchedulers.mainThread().createWorker().schedule(new Action0() {
            @Override
            public void call() {
                String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                PermissionsUtils.getInstance().checkPermission((Activity) context, permissions, "Album", new PermissionsUtils.OnCallBackListener() {
                    @Override
                    public void open(List<String> list) {

                    }

                    @Override
                    public void notOpen(List<String> list, String label) {

                    }
                });
            }
        });
    }

    @JavascriptInterface
    public void getAppInfo() {
        if (mWebView != null) {
            mWebView.post(() -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("versionName", AppInfoUtils.getAppVersionName(context));
                jsonObject.put("versionCode", AppInfoUtils.getAppVersionCode(context));
                jsonObject.put("packageName", AppInfoUtils.getAppPackageName());
                jsonObject.put("channelName", AppInfoUtils.getAppMetaData("UMENG_CHANNEL"));
                mWebView.evaluateJavascript("javascript:setAppInfo('" + jsonObject.toJSONString() + "')", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {

                    }
                });
            });
        }
    }

    @JavascriptInterface
    public void routerJump(String eventName, String json) {
        if (mWebView != null) {
            mWebView.post(() -> {
                JSONObject jsonObject = null;
                if (!TextUtils.isEmpty(json)) {
                    jsonObject = JSONObject.parseObject(json);
                }
                RxBus.getDefault().post(new WebRouterEvent(eventName, jsonObject));
            });
        }
    }

    @JavascriptInterface
    public void appLog(String data) {
        Log.d("web_log", data);
        if (mWebView != null) {
            mWebView.post(() -> {
                mWebView.evaluateJavascript("javascript:appLog('" + data + "')", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {

                    }
                });
            });
        }
    }
}
